<template>
	<view class="page">

		<!-- 顶部标题 -->
		<view class="header">
			<text class="title">图片水印生成工具</text>
			<text class="subtitle">上传图片，自动添加时间与地理位置水印</text>
		</view>

		<view class="content">
			<!-- 图片选择 -->
			<view class="section">
				<view class="section-title">选择图片</view>
				<view class="upload-area" @click="selectImage">
					<u-icon name="photo" size="60" color="#3498db"></u-icon>
					<text class="upload-text">点击选择图片</text>
				</view>
			</view>

			<!-- 图片信息 -->
			<view class="section" v-if="imageInfo">
				<view class="section-title">图片信息</view>
				<u-cell-group>
					<u-cell title="文件名" :value="imageInfo.name"></u-cell>
					<u-cell title="大小" :value="(imageInfo.size / 1024).toFixed(2) + ' KB'"></u-cell>
					<u-cell title="类型" :value="imageInfo.type"></u-cell>
				</u-cell-group>
			</view>

			<!-- 位置 -->
			<view class="section" v-if="location">
				<view class="section-title">位置信息</view>
				<u-cell-group>
					<u-cell title="经纬度" :value="location.longitude + ',' + location.latitude"></u-cell>
					<u-cell title="地址" :value="location.address || '正在获取中...'"></u-cell>
				</u-cell-group>
			</view>

			<!-- 预览 -->
			<view class="section" v-if="watermarkedImage">
				<view class="section-title">预览效果</view>
				<image :src="watermarkedImage" mode="widthFix" class="preview-img"></image>

				<view class="button-group">
					<u-button type="primary" @click="downloadImage">保存图片</u-button>
					<u-button type="success" @click="reset">重新选择</u-button>
				</view>
			</view>
		</view>
		<canvas canvas-id="myCanvas" style="width: 100%; height: 500rpx;"></canvas>
	</view>

</template>

<script>
	export default {
		data() {
			return {
				imageInfo: null,
				originalImage: null,
				watermarkedImage: null,
				location: null,
				currentTime: '',
				appKey: '17199ca42c49b94b31af3a1cc56cc21b'
			};
		},
		onLoad() {
			this.updateTime();
			setInterval(this.updateTime, 1000);
			this.getLocation();
		},
		methods: {
			updateTime() {
				const now = new Date();
				this.currentTime = `${now.getFullYear()}-${(now.getMonth() + 1)
        .toString()
        .padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')} ${now
        .getHours()
        .toString()
        .padStart(2, '0')}:${now
        .getMinutes()
        .toString()
        .padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
			},
			selectImage() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						const path = res.tempFilePaths[0];
						uni.getFileInfo({
							filePath: path,
							success: (info) => {
								this.imageInfo = {
									name: path.split('/').pop(),
									size: info.size,
									type: 'image/jpeg'
								};
								this.originalImage = path;
								this.addWatermark();
							}
						});
					}
				});
			},
			getLocation() {
				uni.showLoading({
					title: '正在获取位置'
				});
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						this.location = {
							longitude: res.longitude,
							latitude: res.latitude,
							address: ''
						};
						this.getReverseGeocode(res.longitude, res.latitude);
					},
					fail: () => {
						uni.hideLoading();
						this.location = {
							longitude: 116.397428,
							latitude: 39.90923,
							address: '北京市东城区'
						};
					}
				});
			},
			getReverseGeocode(longitude, latitude) {
				uni.request({
					url: 'https://restapi.amap.com/v3/geocode/regeo',
					method: 'GET',
					data: {
						key: this.appKey,
						location: `${longitude},${latitude}`,
						output: 'JSON'
					},
					success: (res) => {
						if (res.data.status === '1') {
							this.location.address = res.data.regeocode.formatted_address;
						} else {
							this.location.address = '地址解析失败';
						}
					},
					fail: () => {
						this.location.address = '请求失败';
					},
					complete: () => {
						uni.hideLoading();
					}
				});
			},
			addWatermark() {
				if (!this.originalImage) return;

				uni.getImageInfo({
					src: this.originalImage,
					success: (res) => {
						console.log('图片宽度:', res.width);
						console.log('图片高度:', res.height);
						console.log('图片路径:', res.path);

						const ctx = uni.createCanvasContext('myCanvas', this);

						const imgW = res.width;
						const imgH = res.height;

						// 绘制原图
						ctx.drawImage(res.path, 0, 0, imgW, imgH);

						// 添加水印背景
						ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
						ctx.fillRect(20, imgH - 60, imgW - 40, 40);

						// 添加水印文字
						ctx.font = '16px Arial';
						ctx.fillStyle = 'white';
						ctx.fillText(`时间: ${this.currentTime}`, 30, imgH - 40);
						ctx.fillText(`位置: ${this.location?.address || '获取中...'}`, 30, imgH - 20);

						// 转换为图片

						// 绘制完成并导出图片
						ctx.draw(false, () => {
							uni.canvasToTempFilePath({
								canvasId: 'myCanvas',
								success: (res2) => {
									this.watermarkedImage = res2.tempFilePath;
								},
								fail: (err) => {
									console.error('生成带水印图片失败:', err);
								}
							}, this);
						});

					},
					fail: (err) => {
						console.error('获取图片信息失败:', err);
					}
				});

			},
			downloadImage() {
				if (!this.watermarkedImage) return;

				const link = document.createElement('a');
				link.href = this.watermarkedImage;
				link.download = `watermarked_${new Date().getTime()}.jpg`;
				document.body.appendChild(link);
				link.click();
				document.body.removeChild(link);

				uni.showToast({
					title: '图片保存成功',
					icon: 'success'
				});
			},
			reset() {
				this.imageInfo = null;
				this.originalImage = null;
				this.watermarkedImage = null;
				this.$refs.fileInput.value = '';
			}
		}
	};
</script>

<canvas canvas-id="canvas" style="width: 750rpx; height: 750rpx; display: none"></canvas>

<style scoped>
	.page {
		background: #f5f7fa;
		min-height: 100vh;
	}

	.header {
		background: linear-gradient(90deg, #3498db, #2980b9);
		padding: 30rpx;
		text-align: center;
		color: #fff;
	}

	.title {
		font-size: 36rpx;
		font-weight: bold;
	}

	.subtitle {
		font-size: 24rpx;
		opacity: 0.9;
	}

	.content {
		padding: 30rpx;
	}

	.section {
		margin-bottom: 30rpx;
		background: #fff;
		border-radius: 20rpx;
		padding: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
	}

	.section-title {
		font-size: 28rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
		color: #2c3e50;
	}

	.upload-area {
		border: 2rpx dashed #3498db;
		border-radius: 16rpx;
		padding: 60rpx;
		text-align: center;
		background: #edf7ff;
	}

	.upload-text {
		margin-top: 20rpx;
		font-size: 26rpx;
		color: #666;
	}

	.preview-img {
		width: 100%;
		border-radius: 16rpx;
		margin-top: 20rpx;
	}

	.button-group {
		margin-top: 30rpx;
		display: flex;
		gap: 20rpx;
	}
</style>